async function acquireStudentList() {
  //学生列表渲染

  studentListRender();
  //新增学生

  addStudent();

  //编辑学生

  editStudent();

  //删除学生

  delStudent();
}
//将数字表达性别转化为字符串表达
function genderJudge(gender) {
  if (gender == 0) {
    return "男";
  } else {
    return "女";
  }
}
//将表单的Modal

function getStudentMsg(str) {
  const Modal = new bootstrap.Modal(document.querySelector("#modal"));
  document.querySelector(".modal-title").innerHTML = str;
  Modal.show();
  // areaSetting();

  return Modal;
}

/* async function areaSetting() {
  const proDom = document.querySelector('[name="province"]');
  const cDom = document.querySelector('[name="city"]');
  const aDom = document.querySelector('[name="area"]');
  const province = await axios.get("/api/province");
  const pList = province.data.list;
  const str =
    '<option value="">--省份--</option>' +
    pList.map((item) => `<option value="${item}">${item}</option>`).join("");

  proDom.innerHTML = str;

  proDom.addEventListener("change", async function () {
    const city = await axios.get(`/api/city?pname=${proDom.value}`);
    console.log(city);
    const cList = city.data.list;
    const str =
      '<option value="">--城市--</option>' +
      cList.map((item) => `<option value="${item}">${item}</option>`).join("");
    cDom.innerHTML = str;
    aDom.value = "";
  });
  cDom.addEventListener("change", async function () {
    const area = await axios.get(
      `/api/area?pname=${proDom.value}&cname=${cDom.value}`
    );
    console.log(area);
    const aList = area.data.list;
    const str =
      '<option value="">--地区--</option>' +
      aList.map((item) => `<option value="${item}">${item}</option>`).join("");

    aDom.innerHTML = str;
  });
}
 */
//获取表单中的省市区地址
async function areaReturn(province, city, area) {
  const proDom = document.querySelector('[name="province"]');
  const cDom = document.querySelector('[name="city"]');
  const aDom = document.querySelector('[name="area"]');

  const provinceRes = await axios.get("/api/province");
  const pList = provinceRes.data.list;
  const str =
    '<option value="">--省份--</option>' +
    pList.map((item) => `<option value="${item}">${item}</option>`).join("");
  proDom.innerHTML = str;
  proDom.value = province || "";
  async function getCity() {
    const cityRes = await axios.get(`/api/city?pname=${proDom.value}`);
    const cList = cityRes.data.list;
    const str =
      '<option value="">--城市--</option>' +
      cList.map((item) => `<option value="${item}">${item}</option>`).join("");
    cDom.innerHTML = str;
  }
  await getCity();
  cDom.value = city || "";
  proDom.addEventListener("change", function () {
    getCity();
    aDom.value = "";
    cDom.value = "";
  });
  await getArea();
  aDom.value = area || "";
  async function getArea() {
    const areaRes = await axios({
      url: `/api/area?pname=${proDom.value}&cname=${cDom.value}`,
    });
    const aList = areaRes.data.list;
    const str =
      '<option value="">--地区--</option>' +
      aList.map((item) => `<option value="${item}">${item}</option>`).join("");
    aDom.innerHTML = str;
  }
  cDom.addEventListener("change", function () {
    getArea();
  });
}

//转换对象中的数字字符串为数字类型
function convertStringNumbersToNumbers(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      let value = obj[key];
      // 检查是否是字符串且该字符串表示一个有效的数字
      if (typeof value === "string" && !isNaN(value) && value.trim() !== "") {
        // 尝试转换为数字
        obj[key] = parseInt(value);
        // 或者使用以下方式，它们效果类似：
        // obj[key] = +value;
        // obj[key] = parseFloat(value); // 如果你知道都是小数
        // obj[key] = parseInt(value, 10); // 如果你知道都是整数
      }
      // 如果值也是一个对象，则递归调用函数
      else if (typeof value === "object" && value !== null) {
        convertStringNumbersToNumbers(value);
      }
    }
  }
}

acquireStudentList();
async function studentListRender() {
  const res = await axios.get("/students");

  const data = res.data.data;
  const studentList = document.querySelector(".list");
  document.querySelector(".total").innerHTML = data.length;
  const strStudent = data
    .map(
      (item) => `<tr>
                    <td>${item.name}</td>
                    <td>${item.age}</td>
                    <td>${genderJudge(item.gender)}</td>
                    <td>第${item.group}组</td>
                    <td>${item.hope_salary}</td>
                    <td>${item.salary}</td>
                    <td>${item.province + item.city + item.area}</td>
                    <td data-id="${item.id}">
                      <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                      <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
                    </td>
                  </tr>`
    )
    .join("");
  studentList.innerHTML = strStudent;

  document.querySelector(`.username`).innerHTML =
    localStorage.getItem("username");
}

function addStudent() {
  let Modal;
  document.querySelector("#openModal").addEventListener("click", function () {
    document.querySelector("#form").reset();
    areaReturn();
    Modal = getStudentMsg("添加学员");
  });
  document
    .querySelector("#submit")
    .addEventListener("click", async function (e) {
      e.preventDefault();
      const data = new serialize(document.querySelector("#form"), {
        hash: true,
        empty: true,
      });
      //将对象中的字符串数字转换为数字类型
      convertStringNumbersToNumbers(data);
      try {
        const res = await axios({ url: "/students", method: "POST", data });
        toast(res.data.message);
        if (res.data.message === "添加学生成功") {
          document.querySelector("#form").reset();
          await studentListRender();
          Modal.hide();
        }
      } catch (error) {
        console.dir(error);
      }
    });
}

function editStudent() {
  const list = document.querySelector(".list");
  let id;
  let Modal;
  list.addEventListener("click", async function (e) {
    if (e.target.classList.contains("bi-pen")) {
      id = e.target.parentNode.parentNode.dataset.id;
      (async function stuDataReturn() {
        //数据回显
        const res = await axios.get(`/students/${id}`);
        const data = res.data.data;
        const { province, city, area } = data;
        await areaReturn(province, city, area);
        Modal = getStudentMsg("编辑学员");

        const keys = Object.keys(data);
        keys.forEach((key) => {
          const dom = document.querySelector(`[name='${key}']`);
          if (
            dom !== null &&
            key !== "gender" &&
            key !== "province" &&
            key !== "city" &&
            key !== "area"
          ) {
            dom.value = data[key];
          } else if (key === "gender") {
            document.querySelectorAll(`[name='${key}']`)[
              data[key]
            ].checked = true;
          }
        });
      })();
    }
  });

  (async function submitEdit() {
    document
      .querySelector("#submit")
      .addEventListener("click", async function (e) {
        e.preventDefault();

        const data = new serialize(document.querySelector("#form"), {
          hash: true,
          empty: true,
        });
        //将对象中的字符串数字转换为数字类型
        convertStringNumbersToNumbers(data);

        try {
          const res = await axios({
            url: `/students/${id}`,
            method: "PUT",
            data,
          });

          toast(res.data.message);
          if (res.data.message === "修改学生成功") {
            await studentListRender();
            document.querySelector("#form").reset();
            Modal.hide();
          }
        } catch (error) {
          console.dir(error);
        }
      });
  })(id);
}

function delStudent() {
  document
    .querySelector(".list")
    .addEventListener("click", async function (e) {
      if (e.target.classList.contains("bi-trash")) {
        pxmu
          .diaglog({
            content: {
              text: "确定要删除吗？",
              color: "#f00",
              size: "16px",
              lineHeight: "20px",
            },
            congif: {
              animation: "slidedeg", //自定义动画 动画名详见动画文档
            },
          })
          .then(async function (res) {
            if (res.btn == "right") {
              id = e.target.parentNode.parentNode.dataset.id;
              const res = await axios({
                url: `/students/${id}`,
                method: "DELETE",
              });
              if (res.status == 204) {
                toast("删除成功");
                studentListRender();
              }
            } else {
              //点击了左侧按钮
            }
          });
      }
    });
}